<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文化图片 - 贝壳OC智能应用中心</title>
    <meta name="description" content="文化图片助手，支持连续对话和历史记录">
    <link rel="stylesheet" href="chat-styles.css">
    <script src="config.js"></script>
</head>

<body>
    <!-- 返回按钮 -->
    <div class="back-button" onclick="window.location.href='index.html'">
        <span>←</span> 返回首页
    </div>

    <!-- 主容器 -->
    <div class="chat-container">
        <!-- 头部 -->
        <div class="chat-header">
            <div class="chat-title">
                <div class="chat-icon">🎨</div>
                <h1>文化图片助手</h1>
                <div class="chat-status online">在线</div>
            </div>
            <div class="chat-actions">
                <button class="action-btn" onclick="clearHistory()" title="清空历史">
                    <span>🗑️</span>
                </button>
                <button class="action-btn" onclick="exportHistory()" title="导出对话">
                    <span>📤</span>
                </button>
            </div>
        </div>

        <!-- 对话区域 -->
        <div class="chat-messages" id="chatMessages">
            <div class="welcome-message">
                <div class="message bot-message">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div class="message-text">
                            您好！我是文化图片创作助手，专门帮助您根据命题结合沉淀数据生成条漫，提供多样化的创意表达方式，让企业文化传播更加生动有趣。请告诉我您想要创作什么主题的文化图片？
                        </div>
                        <div class="message-time">刚刚</div>
                        <div class="message-actions">
                            <button class="copy-btn" onclick="copyMessage(this)" title="复制消息">
                                <span>📋</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-container">
            <div class="chat-input-wrapper">
                <textarea id="chatInput" placeholder="请输入您想要创作的文化图片主题..." rows="1" onkeydown="handleKeyDown(event)"
                    oninput="autoResize(this); toggleSendButton()"></textarea>
                <button id="sendButton" onclick="sendMessage()" disabled>
                    <span class="send-icon">📤</span>
                </button>
            </div>
            <div class="input-tips">
                <span>按 Enter 发送，Shift + Enter 换行</span>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let chatHistory = [];
        let isTyping = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function () {
            console.log('DOM加载完成');
            loadChatHistory();
            console.log('页面初始化完成');
        });

        // 处理键盘事件
        function handleKeyDown(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // 自动调整输入框高度
        function autoResize(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
        }

        // 切换发送按钮状态
        function toggleSendButton() {
            const chatInput = document.getElementById('chatInput');
            const sendButton = document.getElementById('sendButton');
            sendButton.disabled = chatInput.value.trim() === '' || isTyping;
        }

        // 发送消息
        async function sendMessage() {
            const chatInput = document.getElementById('chatInput');
            const message = chatInput.value.trim();

            if (message === '' || isTyping) return;

            console.log('发送消息:', message);

            // 添加用户消息
            addMessage(message, 'user');

            // 清空输入框
            chatInput.value = '';
            chatInput.style.height = 'auto';
            toggleSendButton();

            // 显示机器人正在输入
            showTypingIndicator();

            try {
                // 调用扣子API
                const response = await callCozeAPI(message);
                hideTypingIndicator();
                addMessage(response, 'bot');
            } catch (error) {
                hideTypingIndicator();
                console.error('API调用失败:', error);
                addMessage('抱歉，服务暂时不可用，请稍后再试。错误信息：' + error.message, 'bot');
                showNotification('API调用失败，请检查网络连接', 'error');
            }
        }

        // 调用扣子API
        async function callCozeAPI(query) {
            const apiUrl = CONFIG.getApiUrl('/api/coze-proxy'); // 使用配置的API地址

            const requestBody = {
                bot_id: '7536923888467722286',
                user: 'web_user_' + Date.now(),
                query: query,
                stream: false
            };

            console.log('发送API请求:', requestBody);

            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });

            if (!response.ok) {
                throw new Error('HTTP error! status: ' + response.status);
            }

            const data = await response.json();
            console.log('API响应:', data);

            // 解析响应数据
            if (data.code === 0 && data.messages && data.messages.length > 0) {
                let allContent = [];

                // 收集所有有效的消息内容
                for (const message of data.messages) {
                    const content = message.content || '';
                    if (content.trim() && !content.startsWith('RPCError') && content.length >= 5) {
                        allContent.push(content);
                    }
                }

                // 寻找图片URL
                console.log('开始寻找图片URL，内容数量:', allContent.length);
                for (const content of allContent) {
                    console.log('检查内容:', content.substring(0, 200) + '...');

                    // 只匹配图片文件的URL
                    const imageUrlMatch = content.match(/(https?:\/\/[^\s<>"']+\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?[^\s<>"']*)?)/i);
                    if (imageUrlMatch) {
                        const imageUrl = imageUrlMatch[0];
                        console.log('找到图片URL:', imageUrl);
                        return createImageResponse(imageUrl, content);
                    }

                    // 如果没找到图片，也检查是否有其他类型的媒体链接
                    const mediaUrlMatch = content.match(/(https?:\/\/[^\s<>"']+)/i);
                    if (mediaUrlMatch) {
                        const url = mediaUrlMatch[0];
                        console.log('找到媒体链接:', url);
                        // 如果是PDF或其他文件，提示用户
                        if (url.includes('.pdf')) {
                            return createPdfResponse(url);
                        }
                    }
                }
                console.log('未找到图片URL');

                // 如果没有找到图片URL，返回最后一个有内容的消息
                if (allContent.length > 0) {
                    return allContent[allContent.length - 1];
                }

                return '🤔 没有收到有效的响应内容，请尝试重新发送您的请求。';
            } else {
                console.error('API返回错误:', data);
                return '❌ API调用失败\n\n错误信息：' + (data.msg || '未知错误');
            }
        }

        // 创建图片响应HTML
        function createImageResponse(imageUrl, content) {
            const imageId = 'img_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

            // 创建一个容器div
            const container = document.createElement('div');
            container.innerHTML = '🎉 <strong>图片生成成功！</strong><br><br>';

            // 生成代理链接
            const proxiedImageUrl = CONFIG.getApiUrl('/api/image-proxy?url=' + encodeURIComponent(imageUrl));

            // 显示图片链接（原始链接和代理链接）
            const linkDiv = document.createElement('div');
            linkDiv.style.cssText = 'background: #e3f2fd; padding: 12px; border-radius: 6px; margin: 10px 0; border-left: 4px solid #2196f3;';
            linkDiv.innerHTML = '<strong>🔗 原始链接：</strong><br><a href="' + imageUrl + '" target="_blank" style="color: #1976d2; word-break: break-all; font-size: 12px;">' + imageUrl + '</a><br><br>' +
                '<strong>🌐 代理链接（推荐）：</strong><br><a href="' + proxiedImageUrl + '" target="_blank" style="color: #2e7d32; word-break: break-all; font-size: 12px;">' + proxiedImageUrl + '</a>';
            container.appendChild(linkDiv);

            // 创建图片预览区域
            const previewDiv = document.createElement('div');
            previewDiv.style.cssText = 'background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #e9ecef;';

            // 加载提示
            const loadingDiv = document.createElement('div');
            loadingDiv.id = imageId + '_loading';
            loadingDiv.style.cssText = 'text-align: center; color: #6c757d; font-size: 14px; margin-bottom: 15px;';
            loadingDiv.textContent = '🔄 正在加载图片预览...';

            // 图片元素
            const img = document.createElement('img');
            img.id = imageId;
            img.style.cssText = 'max-width: 100%; max-height: 400px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); display: none;';
            img.alt = '生成的图片';
            img.onload = function () {
                loadingDiv.style.display = 'none';
                img.style.display = 'block';
            };
            img.onerror = function () {
                loadingDiv.style.display = 'none';
                errorDiv.style.display = 'block';
            };

            // 错误提示
            const errorDiv = document.createElement('div');
            errorDiv.id = imageId + '_error';
            errorDiv.style.cssText = 'display: none; color: #dc3545; font-size: 14px; margin-top: 10px; text-align: center;';
            errorDiv.textContent = '⚠️ 图片预览失败，可能需要通过代理访问';

            // 操作按钮容器
            const buttonsDiv = document.createElement('div');
            buttonsDiv.style.cssText = 'text-align: center; margin-top: 15px;';

            // 复制原始链接按钮
            const copyBtn = document.createElement('button');
            copyBtn.style.cssText = 'background: #007bff; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin: 0 4px; cursor: pointer; font-size: 13px;';
            copyBtn.textContent = '📋 复制原始链接';
            copyBtn.onclick = function () {
                copyToClipboard(imageUrl);
            };

            // 复制代理链接按钮
            const copyProxyBtn = document.createElement('button');
            copyProxyBtn.style.cssText = 'background: #2e7d32; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin: 0 4px; cursor: pointer; font-size: 13px;';
            copyProxyBtn.textContent = '📋 复制代理链接';
            copyProxyBtn.onclick = function () {
                copyToClipboard(proxiedImageUrl);
            };

            // 查看按钮（使用代理链接）
            const viewBtn = document.createElement('button');
            viewBtn.style.cssText = 'background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin: 0 4px; cursor: pointer; font-size: 13px;';
            viewBtn.textContent = '👁️ 新窗口查看';
            viewBtn.onclick = function () {
                window.open(proxiedImageUrl, '_blank');
            };

            // 链接详情
            const details = document.createElement('details');
            details.style.cssText = 'margin-top: 15px;';

            const summary = document.createElement('summary');
            summary.style.cssText = 'cursor: pointer; color: #6c757d; font-size: 13px;';
            summary.textContent = '🔗 查看原始链接';

            const detailsLinkDiv = document.createElement('div');
            detailsLinkDiv.style.cssText = 'margin-top: 8px; padding: 8px; background: white; border-radius: 4px; border: 1px solid #dee2e6;';

            const code = document.createElement('code');
            code.style.cssText = 'word-break: break-all; font-size: 11px; color: #495057;';
            code.textContent = imageUrl;

            // 组装元素
            detailsLinkDiv.appendChild(code);
            details.appendChild(summary);
            details.appendChild(detailsLinkDiv);

            buttonsDiv.appendChild(copyBtn);
            buttonsDiv.appendChild(copyProxyBtn);
            buttonsDiv.appendChild(viewBtn);

            previewDiv.appendChild(loadingDiv);
            previewDiv.appendChild(img);
            previewDiv.appendChild(errorDiv);
            previewDiv.appendChild(buttonsDiv);
            previewDiv.appendChild(details);

            container.appendChild(previewDiv);

            // 添加使用提示
            const tips = document.createElement('div');
            tips.innerHTML = '💡 <strong>使用提示：</strong><br>• 点击"新窗口查看"在新标签页中打开图片<br>• 复制链接可以分享给其他人<br>• 建议及时保存，链接可能有时效性<br>';
            container.appendChild(tips);

            // 延迟加载图片
            setTimeout(function () {
                img.src = imageUrl;
            }, 500);

            return container.innerHTML;
        }

        // 创建PDF响应
        function createPdfResponse(url) {
            return '📄 <strong>系统返回了文档链接</strong><br><br>' +
                '当前返回的是PDF文档，不是图片文件。<br><br>' +
                '<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 15px 0; border: 1px solid #e9ecef;">' +
                '<div style="text-align: center; margin-bottom: 15px;">📄 PDF文档</div>' +
                '<div style="text-align: center; margin-top: 15px;">' +
                '<button onclick="copyToClipboard(\'' + url + '\')" style="background: #007bff; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin: 0 4px; cursor: pointer; font-size: 13px;">📋 复制PDF链接</button>' +
                '<button onclick="window.open(\'' + url + '\', \'_blank\')" style="background: #28a745; color: white; border: none; padding: 8px 16px; border-radius: 4px; margin: 0 4px; cursor: pointer; font-size: 13px;">👁️ 查看PDF文档</button>' +
                '</div></div>' +
                '💡 <strong>获取图片的建议：</strong><br>' +
                '• 请尝试更明确的图片生成请求，如"生成一张关于企业文化的图片"<br>' +
                '• 或者询问"能否将这个内容制作成图片形式"<br>' +
                '• 当前机器人可能返回的是相关文档而非图片';
        }

        // 复制到剪贴板函数
        function copyToClipboard(text) {
            console.log('=== 复制功能调用 ===');
            console.log('要复制的文本:', text);

            // 尝试使用现代API
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(function () {
                    console.log('现代API复制成功');
                    showNotification('✅ 链接已复制到剪贴板！', 'success');
                }).catch(function (err) {
                    console.error('现代API复制失败:', err);
                    fallbackCopy(text);
                });
            } else {
                fallbackCopy(text);
            }
        }

        // 备用复制方法
        function fallbackCopy(text) {
            console.log('使用备用复制方法');

            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-9999px';
            textArea.style.top = '-9999px';
            textArea.style.opacity = '0';
            document.body.appendChild(textArea);

            try {
                textArea.focus();
                textArea.select();
                textArea.setSelectionRange(0, 99999);

                const successful = document.execCommand('copy');
                console.log('备用复制结果:', successful);

                if (successful) {
                    showNotification('✅ 链接已复制到剪贴板！', 'success');
                } else {
                    showCopyDialog(text);
                }
            } catch (err) {
                console.error('备用复制异常:', err);
                showCopyDialog(text);
            } finally {
                document.body.removeChild(textArea);
            }
        }

        // 显示复制对话框
        function showCopyDialog(text) {
            const dialog = document.createElement('div');
            dialog.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); display: flex; justify-content: center; align-items: center; z-index: 10000;';

            const content = document.createElement('div');
            content.style.cssText = 'background: white; padding: 20px; border-radius: 10px; max-width: 90%;';

            content.innerHTML = '<h3>📋 复制链接</h3><p>请手动复制以下链接：</p>';

            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.readOnly = true;
            textarea.style.cssText = 'width: 100%; height: 100px; padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-family: monospace;';

            const closeBtn = document.createElement('button');
            closeBtn.textContent = '关闭';
            closeBtn.style.cssText = 'background: #007bff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; margin-top: 15px; float: right;';
            closeBtn.onclick = function () {
                dialog.remove();
            };

            content.appendChild(textarea);
            content.appendChild(closeBtn);
            dialog.appendChild(content);
            document.body.appendChild(dialog);

            textarea.focus();
            textarea.select();

            dialog.onclick = function (e) {
                if (e.target === dialog) {
                    dialog.remove();
                }
            };

            showNotification('⚠️ 请手动复制链接', 'warning');
        }

        // 添加消息到聊天区域
        function addMessage(text, sender, timestamp = null) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            const time = timestamp || getCurrentTime();

            messageDiv.className = 'message ' + sender + '-message';

            const avatar = document.createElement('div');
            avatar.className = 'message-avatar';
            avatar.textContent = sender === 'user' ? '👤' : '🤖';

            const content = document.createElement('div');
            content.className = 'message-content';

            const messageText = document.createElement('div');
            messageText.className = 'message-text';
            messageText.innerHTML = formatMessage(text);

            const messageTime = document.createElement('div');
            messageTime.className = 'message-time';
            messageTime.textContent = time;

            const actions = document.createElement('div');
            actions.className = 'message-actions';

            const copyBtn = document.createElement('button');
            copyBtn.className = 'copy-btn';
            copyBtn.title = '复制消息';
            copyBtn.innerHTML = '<span>📋</span>';
            copyBtn.onclick = function () {
                copyMessage(this);
            };

            actions.appendChild(copyBtn);
            content.appendChild(messageText);
            content.appendChild(messageTime);
            content.appendChild(actions);
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(content);
            chatMessages.appendChild(messageDiv);

            scrollToBottom();

            // 保存到历史记录
            const messageData = {
                text: text,
                sender: sender,
                timestamp: time,
                id: Date.now() + Math.random()
            };

            chatHistory.push(messageData);
            saveChatHistory();
        }

        // 格式化消息文本
        function formatMessage(text) {
            // 如果已经是HTML格式，直接返回
            if (text.includes('<')) {
                return text;
            }

            // 处理换行
            text = text.replace(/\n/g, '<br>');

            // 处理URL链接
            const urlRegex = /(https?:\/\/[^\s<>"']+)/g;
            text = text.replace(urlRegex, '<a href="$1" target="_blank" rel="noopener noreferrer" style="color: #007bff; text-decoration: none;">$1</a>');

            return text;
        }

        // 显示输入指示器
        function showTypingIndicator() {
            if (document.querySelector('.typing-indicator')) return;

            isTyping = true;
            toggleSendButton();

            const chatMessages = document.getElementById('chatMessages');
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message bot-message typing-message';

            const avatar = document.createElement('div');
            avatar.className = 'message-avatar';
            avatar.textContent = '🤖';

            const content = document.createElement('div');
            content.className = 'message-content';

            const indicator = document.createElement('div');
            indicator.className = 'typing-indicator';

            for (let i = 0; i < 3; i++) {
                const dot = document.createElement('div');
                dot.className = 'typing-dot';
                indicator.appendChild(dot);
            }

            content.appendChild(indicator);
            typingDiv.appendChild(avatar);
            typingDiv.appendChild(content);
            chatMessages.appendChild(typingDiv);

            scrollToBottom();
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            isTyping = false;
            toggleSendButton();

            const typingMessage = document.querySelector('.typing-message');
            if (typingMessage) {
                typingMessage.remove();
            }
        }

        // 复制消息
        function copyMessage(button) {
            const messageText = button.closest('.message-content').querySelector('.message-text');
            const text = messageText.innerText || messageText.textContent;
            copyToClipboard(text);
        }

        // 清空历史记录
        function clearHistory() {
            if (confirm('确定要清空所有对话历史吗？此操作不可撤销。')) {
                chatHistory = [];
                saveChatHistory();

                const chatMessages = document.getElementById('chatMessages');
                chatMessages.innerHTML = '';

                // 重新添加欢迎消息
                const welcomeDiv = document.createElement('div');
                welcomeDiv.className = 'welcome-message';
                welcomeDiv.innerHTML = '<div class="message bot-message"><div class="message-avatar">🤖</div><div class="message-content"><div class="message-text">您好！我是文化图片创作助手，请告诉我您想要创作什么主题的文化图片？</div><div class="message-time">刚刚</div><div class="message-actions"><button class="copy-btn" onclick="copyMessage(this)" title="复制消息"><span>📋</span></button></div></div></div>';
                chatMessages.appendChild(welcomeDiv);

                showNotification('对话历史已清空', 'success');
            }
        }

        // 导出对话历史
        function exportHistory() {
            if (chatHistory.length === 0) {
                showNotification('暂无对话记录可导出', 'warning');
                return;
            }

            let exportText = '贝壳OC文化图片助手 - 对话记录\n';
            exportText += '导出时间: ' + new Date().toLocaleString() + '\n';
            exportText += '='.repeat(50) + '\n\n';

            chatHistory.forEach(function (message, index) {
                const sender = message.sender === 'user' ? '用户' : '助手';
                exportText += (index + 1) + '.[' + message.timestamp + '] ' + sender + ': \n' + message.text + '\n\n';
            });

            const blob = new Blob([exportText], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '文化图片对话记录_' + new Date().toISOString().slice(0, 10) + '.txt';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showNotification('对话记录已导出', 'success');
        }

        // 保存聊天历史
        function saveChatHistory() {
            try {
                localStorage.setItem('cultureImageChatHistory', JSON.stringify(chatHistory));
            } catch (error) {
                console.warn('保存聊天历史失败:', error);
            }
        }

        // 加载聊天历史
        function loadChatHistory() {
            try {
                const saved = localStorage.getItem('cultureImageChatHistory');
                if (saved) {
                    chatHistory = JSON.parse(saved);
                    console.log('加载聊天历史:', chatHistory.length, '条记录');

                    // 重新显示历史消息（跳过欢迎消息）
                    if (chatHistory.length > 0) {
                        const chatMessages = document.getElementById('chatMessages');
                        chatMessages.innerHTML = ''; // 清空欢迎消息

                        chatHistory.forEach(function (msg) {
                            addMessage(msg.text, msg.sender, msg.timestamp);
                        });
                    }
                }
            } catch (error) {
                console.warn('加载聊天历史失败:', error);
                chatHistory = [];
            }
        }

        // 滚动到底部
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 显示通知
        function showNotification(message, type) {
            type = type || 'info';
            const notification = document.createElement('div');
            notification.className = 'notification notification-' + type;
            notification.textContent = message;

            const bgColor = type === 'success' ? '#4CAF50' :
                type === 'warning' ? '#FF9800' :
                    type === 'error' ? '#f44336' : '#2196F3';

            notification.style.cssText = 'position: fixed; top: 20px; right: 20px; background: ' + bgColor + '; color: white; padding: 12px 20px; border-radius: 8px; z-index: 10000; animation: slideInRight 0.3s ease; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 300px; word-wrap: break-word;';

            document.body.appendChild(notification);

            setTimeout(function () {
                notification.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(function () {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        // 添加通知动画样式
        const style = document.createElement('style');
        style.textContent = '@keyframes slideInRight { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes slideOutRight { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } }';
        document.head.appendChild(style);

        console.log('所有脚本加载完成');
    </script>
</body>

</html>